import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Toast } from 'vant'

// 创建axios实例
const service = axios.create({
  // baseURL: '',
  timeout: 60000 // 请求超时时间（毫秒）
})

// request请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = store.getters.token
    }
    return config
  },
  error => {
    Toast.fail(error || 'error')
    return Promise.reject(error || 'error')
  }
);

// respone响应拦截器
service.interceptors.response.use(
  response => {
    const { status, data } = response
    if (status == 200) {
      if (data.code !== 200) {
        switch (data.code) {
          case 401:
            // 如果来自 login 页面 则不再进行跳转了
            if (router.currentRoute.path != '/login') {
              store.dispatch('user/resetToken').then(() => {
                router.replace({ path: '/login', query: {
                  redirect: router.currentRoute.fullPath, 
                  msg: data.message 
                }})
              })
            }
            break;
          case 403:
            router.push({ path: '/403', query: { msg: data.message } })
            break;
          case 404:
            router.push({ path: '/404', query: { msg: data.message } })
        }
        Toast.fail(data.message || 'error')
        return Promise.reject(new Error(data.message || 'error'))
      } else {
        return data
      }
    } else {
      Toast.fail(status + '')
      return Promise.reject(new Error(status))
    }
  }
);

export default service